<template>
    <el-form 
        ref="formRef" 
        :model="model" 
        status-icon 
        :rules="rules" 
        label-width="120px" 
        class="myform"
    >
        <el-form-item label="账号" prop="account">
            <el-input :prefix-icon="User" clearable v-model="model.account" type="text" placeholder="请输入账号(用户名或手机号)"
                autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input  :prefix-icon="Lock" clearable v-model="model.password" type="password"
                show-password placeholder="请输入密码" autocomplete="off" />
        </el-form-item>

        <el-form-item class="lastitem">
            <div class="alinks">
                <router-link class="litem " to="/reg">立即注册</router-link>
                <router-link class="litem bg" to="/findpass">找回密码</router-link>
            </div>
        </el-form-item>

        <el-form-item class="lastitem">
            <el-button type="success" block class="btnblock" @click="submitForm(formRef)">登录</el-button>
            <el-button type="danger" block class="btnblock" @click="resetForm(formRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>


<script lang="ts" setup>
import {ref,reactive, onMounted}  from 'vue'
import { Calendar, Search ,Lock , User  , Cellphone} from '@element-plus/icons-vue'
import { formRefType, userInfoFace } from '../../utils/types';
import type{  FormRules } from 'element-plus'
import { reg } from '../../utils/validate';
import { ShowError } from '../../utils/message';
import { Http } from '../../api/api';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
const model = reactive<userInfoFace >({})
const formRef = ref<formRefType>()
const rules = reactive<FormRules>({
    account:[
        { required: true, message: '账号不能为空', trigger: 'blur' },
    ],
    password:[
        { required: true, message: '密码不能为空', trigger: 'blur' },
        {
            pattern:reg.pwd,
            message: '请输入6-16位数字加字母的密码'
        }
    ],
})

const submitForm = (formEl:formRefType)=>{
    if(!formEl) return;
    formEl.validate(async (valid:boolean)=>{
        if(valid){
            console.log(model)
            let res = await Http.login(model) as unknown as any;
            if(res.code==200){
                router.push("/main")
                localStorage.setItem('account',model.account);
                localStorage.setItem("phone",res.result.phone)
                // token 
                sessionStorage.setItem("token",res.token)
            }
        }else{
            ShowError('登录数据正则有误')
        }
    })
}

const resetForm = (formEl:formRefType)=>{
    if(!formEl) return;
    formEl.resetFields()
}

onMounted(()=>{
    console.log(route)
    if(route.query.username){
        model.account = route.query.username
    }else{
        model.account = localStorage.getItem('account')
    }
})
</script>
